import router from '@/lib/router/index';
import store from '@/extend/store';
import { beforeRouter, afterRouter } from '@/lib/router/permission';
import asyncRoutes from './module/index';
// import detail from './module/detail';
import { api_GET_MessageGetUnReadMessagesTotal } from '@/extend/api/swaggerApi/chat.js';
import { api_GET_MallStoreCurrent } from '@/extend/api/shoppingmallswaggerApi/app.js';
import { Message } from 'element-ui';
import { judgeToLogout } from '@/lib/oidc_fun';
import { clearOut } from '@/lib/store/modules/user';
import { getToken, setToken, getUserToken } from '@/lib/auth';

const whiteList = ['/login', '/forgetPassword', '/register', '/recgamedetail']; // no redirect whitelist
// 路由跳转检测
router.beforeEach((to, from, next) => {
  if (to.query.token) {
    if (!store.state.app.isgetBadge) {
      setToken(to.query.token);
    }
  }

  if (to.path !== '/' && getToken()) { // true 表示非第一次
    // 如果没有道馆版本，重定向到根目录
    const _ouEdition = store.state.user.info.organizationUnitEdition;
    if (!_ouEdition || !_ouEdition.isValid) {
      next({ path: '/' });
      store.dispatch('app/setIsGetBadge', false);
      return false;
    }
  }

  beforeRouter(to, from, next, store, router, [...asyncRoutes], whiteList, initToDo).then(() => {
    next();
  }, () => {
    next();
  });
});

router.afterEach(() => {
  afterRouter();
});

// 初始化只执行一次的操作
async function initToDo (to, next) {
  // 获取当前用户注册类型（根据用户类型跳转至对应页面）
  // TODO 获取徽标数据
  if (store.state.user.info.permissions.includes('Chat.Messaging.Read')) {
    api_GET_MessageGetUnReadMessagesTotal().then(res => {
      store.dispatch('permission/setRouterBadge', { Inbox: res });
    });
  }
  await getUserToken();
  if (!store.state.user.info || store.state.user.info.permissions.length <= 0) {
    Message.error('该账号无任何权限，请联系管理员添加权限！');
    const tenantId =
      store.state.user.info && store.state.user.info.tenantId
        ? store.state.user.info.tenantId
        : to.query.tenantid ? to.query.tenantid : '';
    clearOut();
    setTimeout(() => {
      judgeToLogout(window.location.origin + window.location.pathname + '#/?tenantid=' + tenantId);
      // mgr.signinRedirect({
      //   state: window.btoa(window.location.href),
      //   acr_values: router.currentRoute.query.tenantid ? window.btoa(router.currentRoute.query.tenantid) : ''
      // }); // 跳转登录
    }, 1000);
  }
  // 获取路由信息
  const routers = await store.dispatch('user/getRouter');
  console.log(routers);
  // 根据权限获取当前路由表
  // extendRouterList = extendRouterList ? extendRouterList : [];
  const tenantId = store.state.user.info && store.state.user.info.tenantId
    ? store.state.user.info.tenantId
    : to.query.tenantid ? to.query.tenantid : '';
  const accessRoutes = await store.dispatch('permission/generateRoutes', { routers, extendRouterList: [...asyncRoutes], tenantId });
  // 添加动态路由
  console.log(accessRoutes);
  console.log(router.options.routes);
  router.options.routes = [...router.options.routes, ...accessRoutes];
  console.log(router.options.routes);
  await router.addRoutes(accessRoutes);
  // TODO 获取店铺数据
  if (store.state.user.info.permissions.includes('Mall.Store')) {
    await api_GET_MallStoreCurrent({ IncludeStatus: true }).then(res => {
      console.log('shopings-----------', res);
      if (res) {
        const _id = res.id || '';
        store.commit('permission/SET_STOREID', _id);
      }
    }, error => {
      const _msg = error.error.message || error.message;
      Message({ type: 'error', message: _msg });
    });
  }
  console.log(to);
  let _to = to;
  store.dispatch('app/setIsGetBadge', true);
  if (!to.params.tenantId) {
    if (to.path === '/') {
      _to = { name: 'baserouter', params: { tenantId: 't__' + tenantId }};
    } else {
      console.log(2);
      if (!/^\/t__/.test(to.path)) {
        next({ ..._to, ...{ path: '/t__' + tenantId + to.path }, replace: true });
      }
      _to.params.tenantId = '/t__' + tenantId;
      console.log(3);
    }
    next({ ..._to, replace: true });
  }
  if (!/^\/t__/.test(to.path)) {
    next({ ..._to, ...{ path: '/t__' + tenantId + to.path }, replace: true });
  }
  return true;
}

export default router;
